<?php
/**
 * @package		Youjoomla Extend Elements
 * @author		Youjoomla LLC
 * @website     Youjoomla.com 
 * @copyright	Copyright (c) 2007 - 2010 Youjoomla LLC.
 * @license   PHP files are GNU/GPL V2. CSS / JS / IMAGES are Copyrighted Commercial
 */
//<field name="handler" type="yjhandler"/>   add once in xml to load custom codes

// Check to ensure this file is within the rest of the framework
// no direct access 
if((int)JVERSION == 3){
	defined('JPATH_PLATFORM') or die;
}else{
	defined('_JEXEC') or die ('Restricted access');
}
//defined('JPATH_BASE') or die();

/**
 * Renders a spacer element
 *
 * @package 	Joomla.Framework
 * @subpackage		Parameter
 * @since		1.5
 */

class JFormFieldYjHandler extends JFormField
{
	/**
	* Element name
	*
	* @access	protected
	* @var		string
	*/
	
	var	$type = 'YjHandler';
	
	public function getInput(){
	
		$e_folder = basename(dirname(dirname(__FILE__)));
		
		$document = JFactory::getDocument();
		$document->addStyleSheet(JURI::root() . 'plugins/system/'.$e_folder.'/elements/css/custom.css');
		$document->addScript(JURI::root() . 'media/jui/js/jquery.min.js');
		$document->addScript(JURI::root() . 'media/jui/js/jquery-noconflict.js');
		$document->addScript(JURI::root() . 'media/jui/js/bootstrap.min.js');

		//Backup the output file
		jimport('joomla.filesystem.file');
		jimport('joomla.filesystem.folder');		
		$params_obj = $this->form->getValue('params');
		
		$params 	= new JRegistry();
		$params->loadObject($params_obj);
		
		// Create a new query object.
		$db		= JFactory::getDbo();
		$query	= $db->getQuery(true);

		// Select the required fields from the table.
		$query->select('a.template');
		$query->from($db->quoteName('#__template_styles').' AS a');
		$query->where('a.home = 1');
		$query->where('a.client_id = 0');
		
		$db->setQuery($query);
		$default_template = $db->loadResult();		

		// Make sure there aren't any errors
		if ($db->getErrorNum()) {
			echo $db->getErrorMsg();
			exit;
		}
		$yjsg_check 		= JPATH_SITE.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR.$default_template.DIRECTORY_SEPARATOR."yjsgcore".DIRECTORY_SEPARATOR."lessc.inc.php";
		
		
		$input_param		= $params->get('input_file','template');
		$input_file			= JPATH_SITE.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR.$default_template.DIRECTORY_SEPARATOR."less".DIRECTORY_SEPARATOR.$input_param.".less";
		
		$output_param		= $params->get('output_file','template');
		$output_folder		= $params->get('output_folder','css');
		$output_file		= JPATH_SITE.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR.$default_template.DIRECTORY_SEPARATOR.$output_folder.DIRECTORY_SEPARATOR.$output_param.".css";
		$formated_output 	= str_replace("/","_dir_",$output_folder)."_dir_".str_replace("/","_dir_",$output_param).".css";

		$backup_folder		= JPATH_SITE.DIRECTORY_SEPARATOR."plugins".DIRECTORY_SEPARATOR."system".DIRECTORY_SEPARATOR.$e_folder.DIRECTORY_SEPARATOR."backups";
		
		
	if(!JFile::exists($yjsg_check)){// load this baby only if is not YJSG template	
		//check if the file exists
		if(!JFile::exists($input_file)){
			JError::raiseNotice('200', JText::_('PLG_SYSTEM_JBOOTSTRAP_INPUTFILE_NOT_FOUND')."<br/>".$input_file);
		}
				
		if(!JFile::exists($output_file)){
			JError::raiseNotice('200', JText::_('PLG_SYSTEM_JBOOTSTRAP_OUTPUTFILE_NOT_FOUND')."<br/>".$output_file);
		}else{
			//create backup only if the file does not exists
			if(!JFile::exists($backup_folder.DIRECTORY_SEPARATOR.$formated_output)){
				//copy the file to the backups folder
				if(!JFolder::exists(JPATH_SITE . "/plugins/system/".$e_folder."/backups")){
					JFolder::create(JPATH_SITE . "/plugins/system/".$e_folder."/backups");
				}
				if(JFile::copy($output_file, $backup_folder.DIRECTORY_SEPARATOR.$formated_output)){
					@chmod($backup_folder.DIRECTORY_SEPARATOR.$formated_output, 0777);
					$app = JFactory::getApplication();
					$app->enqueueMessage(sprintf(JText::_('PLG_SYSTEM_JBOOTSTRAP_BACKUP_SUCCESSFULLY'),$output_param.".css"));
				}
			}
		}
	}else{
		$document->addCustomTag('<style type="text/css">.noyjsg, .panelform .hasTip{display:none!important;}</style>');
	}//yjsg check
?>

<div class="container">
<?php if(JFile::exists($yjsg_check)){ ?>
	<br /><br />
  <div class="alert alert-error">
  <?php echo JText::_('PLG_SYSTEM_JBOOTSTRAP_YJSG_MSG'); ?>
  </div>
<?php } ?>

  <p class="jb_button_holder"><a class="btn btn-success btn-large  font-open-sans-normal pull-left" href="#JBootstrap_in" data-toggle="modal"><strong>JBootstrap Instructions</strong></a></p>
</div>
</div>
<div id="JBootstrap_in" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h2 id="myModalLabel">JBootstrap Instructions</h2>
  </div>
  <div class="modal-body">

<h3>About this plugin</h3>
    <p> JBootstrap is a Joomla! system plugin that brings <a href="http://twitter.github.com/bootstrap/" target="_blank">Twitter Bootstrap</a> functionality in Joomla! 2.5.
      This plugin is using default Joomla 3.x <code>bootstrap.framework</code> method for Joomla and 
      this way  making sure that your template conversion from Joomla!  2.5  to 3.x will be 
      Joomla <code>boostrap.framework</code> compatible. The location of bootstrap framework <code>js/css</code> files is 
      same as in Joomla! 3.x . You can test the compatibility by installing Protostar Joomla! 3.0 Template on Joomla 2.5<br />
      <br />
      Beside Twitter Bootstrap, this plugin also includes optional LESS files compiler php class. <code>lessphp</code> developed by <a href="http://leafo.net/lessphp/" target="_blank">leafo</a> .<br />
      <br />
  </p>
    <div class="alert alert-error">
      <h4>&nbsp;</h4>
      <h4>Notice!</h4>
      Please note that in no way does this plugin applies needed <code>tags/class</code> names to your templates. It simply includes the framework 
      to style them. You would still need to edit your templates and adapt them for <a href="http://twitter.github.com/bootstrap/" target="_blank">Twitter Bootstrap use.</a> <br />
      <br />
      
  </div>

    <h3>How to use JBootstrap plugin</h3>
    <h4>Include boostrap.framework in your template:</h4>
    <p> In  your template <code>index.php</code> file add  call for <code>boostrap.framework</code>
    <pre>JHtml::_('bootstrap.framework');</pre>
    Position it under
  <pre>JHtml::_('behavior.framework',true);</pre>
    so it looks like
  <pre>     JHtml::_('behavior.framework',true);
     JHtml::_('bootstrap.framework');     </pre>
    
 </p>
 <p>This method will include needed Java script files for Twitter Bootstrap.</p>
<h4>Include bootstrap css files Option 1:</h4>
    <p> Above your <code>template css files</code>  calls i.e.<br>
  <pre>$doc->addStyleSheet('templates/'.$this->template.'/css/template.css');</pre>
      add :
    <pre>JHtmlBootstrap::loadCss();</pre>
    so it looks like 
  <pre>
    JHtmlBootstrap::loadCss();
    $doc->addStyleSheet('templates/'.$this->template.'/css/template.css');    </pre>
    <p>This will include , <code>boostrap.css</code> and <code>boostrap.css fixes</code> style sheets within your head tag and position them above your template.css file.</p>
  <p>&nbsp; </p>
    <h4>JHtmlBootstrap::loadCss() Optional:</h4>
    If true, main <code>bootstrap.css</code> file is loaded<br /><br />
    <pre>
@param   boolean  $includeMainCss 
JHtmlBootstrap::loadCss($includeMaincss = true);      </pre>
    rtl or ltr direction. If empty, ltr is assumed
    	<pre>
JHtmlBootstrap::loadCss($includeMaincss = true,$this->direction);       </pre>
 		or
  <pre>
JHtmlBootstrap::loadCss($includeMaincss = false,$this->direction);       </pre>
  <h4>&nbsp;</h4>
  <h4>Include bootstrap css file Option 2:</h4>
    <ol>
      <li> create less folder in your template root i.e.<br />
      <code>site_root/templates/temlpate_name/less</code> </li>
      <li> Set Activate compiler parameter to <strong>Yes</strong>. </li>
      <li> Define your Input LESS file name </li>
      <li> Define your Output CSS file name. </li>
      <li> Hit Apply </li>
      <li> If your Output CSS file name is different than <code>template.css</code> please remember
        to include call for this css file in your template head. i.e.<br /><br />
        <pre>$doc->addStyleSheet('templates/'.$this->template.'/css/new_file_name.css');</pre>
      </li>
  </ol>
    </p>
  <h3>Compile process explained:</h3>
    <p> If you turn the compiler on , it generates new output CSS file from your LESS input file and places it in your 
      <code>template/css</code> folder. This plugin is using extend lessphp
    classes <code>lessPhpCache</code> and <code>lessPhpCss</code> which are included in plugin. Our <code>lessPhpCache</code> class is extending default lessphp <code>$less->cachedCompile()</code> method 
    which is optimized for speed and compiles your main LESS file if there were any changes to main file itself or any files included <code>@import</code> .</p>
    <h3>lessphpCss extend lessphp Explained:</h3>
    <p> Since lessphp by default compiles only LESS files , this JBootstrap plugin param option will let you compile LESS and CSS files in to 1 CSS file.
      This is useful if you have <code>@import</code> files within your main css style sheet
    and would like to reduce the number of http requests.
    <h4>Example use if Compile CSS files param is on:</h4>
    <p> If you are using include bootstrap css Option 1
      in your <code>file_name.less</code> file add:<br />
    <pre>
@import "../css/template.css";    </pre>
    The extend class will compile <code>template.css</code> with all CSS files <code>@import</code> 
    that are included and this way you don't have to create new less files. <br />
    <br />
    If you are using Option 2 in your <code>file_name.less</code> file add:<br />
    <br />
  <pre>
@import "bootstrap.less";
@import "../css/template.css";    </pre>
    <p>The extend class will compile <code>boostrap.less</code> with all LESS files <code>@import</code> + <code>template.css</code> with all CSS files <code>@import</code> 
    and this way you don't have to recreate new less files.
    </p>
    </p>
    <p>&nbsp;</p>
    <h3>Should I keep the compiler on at all times?</h3>
    <p>Please understand that compile process is normally used to recompile your LESS file to a CSS file and it should do exactly that when any main LESS depending files are changed. Our suggestion is , keep the compiler on until you are done editing your styles. After that there is no need for it since it will check for files time changed for no reason. Not that time check process is to much for your server to handle but there is no need for any check if you are done with your styles edits.</p>
    <h3>First page load after style edit or plugin params change is slow. Why ?</h3>
    <p>This is completely normal. You have just edited one of your LESS or CSS files that are included in your <code>your_input_file_name.less</code> file. Compiler has noted the change and is recompiling. Next page refresh is much faster.<br>
      <br>
    If you did any changes to the JBootstrap plugin parameters and hit save or apply , plugin is deleting the files times cache and tells compiler to compile again so that you can see the changes applied immediately. </p>
    <h3>Compress css files param</h3>
    <p>Compress CSS files JBootstrap plugin param if turned on removes all white spaces from your newly generated CSS file and with this speeding up page load time. </p>
    <h3> Backup and restore process</h3>
    <p>
    Once you have entered Jboostrap plugin admin area the plugin has already backed up your <code>template.css</code> file so you can restore to default if you wish.
    <br>
    If however your template is not using template.css file name , in Jboostrap plugin param name <code>Output CSS file name</code> add your default style sheet name and once you hit save or apply it will be backed up. To restore your default CSS files , simply set <code>Restore to default</code> param to Yes and hit apply. Your default style sheet will be placed back in your template css folder.
    </p>
  </div>
  <div class="modal-footer">
    <button class="btn btn-success" data-dismiss="modal">Close</button>
  </div>
</div>
<script>
		(function($){
			$('*[rel=tooltip]').tooltip()

						// fix sub nav on scroll
			var $win = $(window)
			  , $nav = $('.subhead')
			  , navTop = $('.subhead').length && $('.subhead').offset().top - 40			  , isFixed = 0

			processScroll()

			// hack sad times - holdover until rewrite for 2.1
			$nav.on('click', function () {
				if (!isFixed) setTimeout(function () {  $win.scrollTop($win.scrollTop() - 47) }, 10)
			})

			$win.on('scroll', processScroll)

			function processScroll() {
				var i, scrollTop = $win.scrollTop()
				if (scrollTop >= navTop && !isFixed) {
					isFixed = 1
					$nav.addClass('subhead-fixed')
				} else if (scrollTop <= navTop && isFixed) {
					isFixed = 0
					$nav.removeClass('subhead-fixed')
				}
			}
			
			// Turn radios into btn-group
		    $('.radio.btn-group label').addClass('btn');
		    $(".btn-group label:not(.active)").click(function() {
		        var label = $(this);
		        var input = $('#' + label.attr('for'));

		        if (!input.prop('checked')) {
		            label.closest('.btn-group').find("label").removeClass('active btn-success btn-danger btn-primary');
		            if(input.val()== '') {
		                    label.addClass('active btn-primary');
		             } else if(input.val()==0) {
		                    label.addClass('active btn-danger');
		             } else {
		            label.addClass('active btn-success');
		             }
		            input.prop('checked', true);
		        }
		    });
		    $(".btn-group input[checked=checked]").each(function() {
				if($(this).val()== '') {
		           $("label[for=" + $(this).attr('id') + "]").addClass('active btn-primary');
		        } else if($(this).val()==0) {
		           $("label[for=" + $(this).attr('id') + "]").addClass('active btn-danger');
		        } else {
		            $("label[for=" + $(this).attr('id') + "]").addClass('active btn-success');
		        }
		    });
		})(jQuery);
	</script>
<?php
		return ; 
	}
	
	public function getLabel() {
		return false;
	}
}

